package com.base.login.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.base.common.constant.Constants;
import com.base.common.core.domain.dto.RoleDTO;
import com.base.common.core.domain.entity.SysUser;
import com.base.common.core.domain.model.LoginUser;
import com.base.common.enums.DeviceType;
import com.base.common.enums.LoginType;
import com.base.common.helper.LoginHelper;
import com.base.common.utils.MessageUtils;
import com.base.login.service.ISysLoginService;
import com.base.system.domain.vo.TSysUserVo;
import com.base.system.service.ITSysUserRoleService;
import com.base.system.service.ITSysUserService;
import com.base.login.domain.bo.SysLoginBo;
import com.base.login.domain.vo.LoginUserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 权限菜单Service业务层处理
 *
 * @author base
 * @date 2023-10-18
 */
@RequiredArgsConstructor
@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private final ITSysUserRoleService itSysUserRoleService;

    @Autowired
    private final ITSysUserService itSysUserService;


    @Override
    public String genRandom() {
        return "1234567887654321";
    }

    @Override
    public String login(SysLoginBo bo) {

        TSysUserVo tSysUserVo = itSysUserService.queryById(bo.getSignCertSn());
        SysUser user = new SysUser();
        BeanUtils.copyProperties(tSysUserVo,user);
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.PC);
        return StpUtil.getTokenValue();
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(SysUser user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId()+"");
        loginUser.setUsername(user.getUserName());
//        loginUser.setUserType(user.getUserType());
//        loginUser.setMenuPermission(permissionService.getMenuPermission(user));
//        loginUser.setRolePermission(permissionService.getRolePermission(user));
        List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
        loginUser.setRoles(roles);
        return loginUser;
    }

    @Override
    public LoginUserVo info() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        TSysUserVo user = itSysUserService.queryById(loginUser.getUserId());
        LoginUserVo userVo = new LoginUserVo();
        return userVo;
    }

    @Override
    public boolean logout() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        StpUtil.logout();
        return true;
    }
}
